package com.fybspace.primary;


import com.fybspace.primary.DAO.UserDAO;
import com.fybspace.primary.Entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * Created by studio on 2017/4/27.
 */

@Service
public class UserDetailService implements UserDetailsService {

    @Autowired
    private UserDAO userDAO;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if (userDAO != null){
            UserEntity user = userDAO.findByUsername(username);

            if (user == null){
                throw new UsernameNotFoundException("用户名不存在");
            }

            //user.getRole()代表权限，格式为ROLE_xxx，例如ROLE_ADMIN，对应角色ADMIN
            GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_"+user.getRole());
            UserDetails userDetails = new User(user.getUsername(),user.getPassword(), Arrays.asList(authority));
            return userDetails;
        }

        return null;
    }
}
